package com.imyuanma.qingyun.common.client.monitor.trace;

import com.imyuanma.qingyun.common.util.StringUtil;
import com.imyuanma.qingyun.common.util.constants.BeanOrderConstants;
import com.imyuanma.qingyun.interfaces.monitor.model.TraceDTO;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.RejectedExecutionException;

/**
 * web层日志切面
 *
 * @author imrookie
 * @date 2018/11/24
 */
@Aspect
@Component
public class TraceAop implements Ordered {

    private static final Logger logger = LoggerFactory.getLogger(TraceAop.class);

    //切面顺序
    @Override
    public int getOrder() {
        return BeanOrderConstants.HIGHEST_PRECEDENCE;
    }

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.imyuanma.qingyun.interfaces.monitor.annotation.Trace)")
    public void pointcut(){
    }

    /**
     * 环绕通知
     * @param joinPoint
     * @return
     */
    @Around("pointcut()")
    public Object around(JoinPoint joinPoint) throws Throwable {
        TraceMeta traceMeta = TraceMeta.start(joinPoint);
        Object result = null;
        Throwable throwable = null;
        try {
            //执行此方法
            result = ((ProceedingJoinPoint)joinPoint).proceed();
        } catch (Throwable e) {
            throwable = e;
            throw e;
        } finally {
            if (traceMeta != null) {
                traceMeta.end(result, throwable);
            }
        }
        return result;
    }

}
